// 记忆翻牌游戏 JavaScript
class MemoryCardGame {
    constructor() {
        this.gameState = null;
        this.selectedCard = null;
        this.cards = [];
        this.init();
    }

    init() {
        this.bindEvents();
        this.showScreen('startScreen');
        this.updateUI();
    }

    bindEvents() {
        // 开始游戏按钮
        document.getElementById('startBtn').addEventListener('click', () => this.startGame());

        // 再玩一次按钮
        document.getElementById('playAgainBtn').addEventListener('click', () => this.resetGame());

        // 排行榜按钮
        document.getElementById('leaderboardBtn').addEventListener('click', () => this.showLeaderboard());

        // 关闭模态框
        document.querySelector('.close').addEventListener('click', () => this.closeModal());

        // 点击模态框外部关闭
        window.addEventListener('click', (e) => {
            const modal = document.getElementById('leaderboardModal');
            if (e.target === modal) {
                this.closeModal();
            }
        });

        // 难度选择变化
        document.getElementById('difficulty').addEventListener('change', () => {
            if (this.gameState && this.gameState.game_phase === 'memorizing') {
                this.resetGame();
            }
        });
    }

    async startGame() {
        try {
            const difficulty = document.getElementById('difficulty').value;
            const response = await fetch('/api/start_game', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({ difficulty })
            });

            const data = await response.json();
            if (data.success) {
                this.cards = data.cards;
                this.showScreen('memoryScreen');
                this.startMemoryPhase(data.show_time);
                this.updateUI();
            } else {
                this.showMessage('启动游戏失败', 'error');
            }
        } catch (error) {
            console.error('启动游戏错误:', error);
            this.showMessage('网络错误，请重试', 'error');
        }
    }

    startMemoryPhase(showTime) {
        this.renderMemoryCards();

        // 开始倒计时
        let countdown = 3;
        const countdownElement = document.getElementById('countdown');

        const countdownInterval = setInterval(() => {
            countdownElement.textContent = countdown;
            countdownElement.style.transform = 'scale(1.2)';

            setTimeout(() => {
                countdownElement.style.transform = 'scale(1)';
            }, 500);

            countdown--;

            if (countdown < 0) {
                clearInterval(countdownInterval);

                // 翻转所有卡牌
                setTimeout(async () => {
                    await this.flipAllCards();
                    this.startTestPhase();
                }, 500);
            }
        }, 1000);
    }

    renderMemoryCards() {
        const cardGrid = document.getElementById('cardGrid');
        cardGrid.innerHTML = '';

        this.cards.forEach((card, index) => {
            const cardElement = document.createElement('div');
            cardElement.className = 'card';
            cardElement.dataset.cardId = card.id;
            cardElement.innerHTML = `
                <span>${card.pattern.emoji}</span>
                <div class="card-label">${card.pattern.name}</div>
            `;

            // 添加入场动画
            cardElement.style.opacity = '0';
            cardElement.style.transform = 'translateY(20px)';
            cardGrid.appendChild(cardElement);

            setTimeout(() => {
                cardElement.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
                cardElement.style.opacity = '1';
                cardElement.style.transform = 'translateY(0)';
            }, index * 100);
        });
    }

    async flipAllCards() {
        try {
            const response = await fetch('/api/flip_cards', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            const data = await response.json();
            if (data.success) {
                // 翻转动画
                const cards = document.querySelectorAll('#cardGrid .card');
                cards.forEach((card, index) => {
                    setTimeout(() => {
                        card.style.transform = 'rotateY(180deg)';
                    }, index * 200);
                });
            }
        } catch (error) {
            console.error('翻转卡牌错误:', error);
        }
    }

    startTestPhase() {
        this.showScreen('testScreen');
        this.renderTestCards();
        this.renderPositionGrid();
        this.clearResultMessage();
    }

    renderTestCards() {
        const cardSelector = document.getElementById('cardSelector');
        cardSelector.innerHTML = '';

        this.cards.forEach((card, index) => {
            const cardElement = document.createElement('div');
            cardElement.className = 'selectable-card';
            cardElement.dataset.cardId = card.id;
            cardElement.innerHTML = card.pattern.emoji;
            cardElement.title = card.pattern.name;

            cardElement.addEventListener('click', () => this.selectCard(card.id));

            // 添加入场动画
            cardElement.style.opacity = '0';
            cardElement.style.transform = 'translateX(-20px)';
            cardSelector.appendChild(cardElement);

            setTimeout(() => {
                cardElement.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
                cardElement.style.opacity = '1';
                cardElement.style.transform = 'translateX(0)';
            }, index * 100);
        });
    }

    renderPositionGrid() {
        const positionGrid = document.getElementById('positionGrid');
        positionGrid.innerHTML = '';

        const cardCount = this.cards.length;

        for (let i = 0; i < cardCount; i++) {
            const positionSlot = document.createElement('div');
            positionSlot.className = 'position-slot';
            positionSlot.dataset.position = i;
            positionSlot.textContent = `位置 ${i + 1}`;

            positionSlot.addEventListener('click', () => this.selectPosition(i));

            // 添加入场动画
            positionSlot.style.opacity = '0';
            positionSlot.style.transform = 'scale(0.8)';
            positionGrid.appendChild(positionSlot);

            setTimeout(() => {
                positionSlot.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
                positionSlot.style.opacity = '1';
                positionSlot.style.transform = 'scale(1)';
            }, i * 100);
        }
    }

    selectCard(cardId) {
        if (this.selectedCard === cardId) {
            this.selectedCard = null;
            document.querySelectorAll('.selectable-card').forEach(card => {
                card.classList.remove('selected');
            });
        } else {
            this.selectedCard = cardId;
            document.querySelectorAll('.selectable-card').forEach(card => {
                card.classList.remove('selected');
            });
            document.querySelector(`[data-card-id="${cardId}"]`).classList.add('selected');
        }

        this.clearResultMessage();
    }

    selectPosition(position) {
        if (this.selectedCard === null) {
            this.showMessage('请先选择一张卡牌！', 'error');
            return;
        }

        // 检查是否已经尝试过这个位置
        const positionSlot = document.querySelector(`[data-position="${position}"]`);
        if (positionSlot.classList.contains('disabled')) {
            this.showMessage('这个位置已经尝试过了！', 'error');
            return;
        }

        this.checkCardPosition(this.selectedCard, position);
    }

    async checkCardPosition(cardId, guessedPosition) {
        try {
            const response = await fetch('/api/check_card', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    card_id: cardId,
                    guessed_position: guessedPosition
                })
            });

            const data = await response.json();
            if (data.success) {
                this.updateUI();
                this.showCheckResult(data, guessedPosition);

                // 禁用已尝试的位置
                const positionSlot = document.querySelector(`[data-position="${guessedPosition}"]`);
                positionSlot.classList.add('disabled');

                if (data.is_correct) {
                    positionSlot.classList.add('correct');
                    // 如果答对了，标记卡牌为已找到
                    const cardElement = document.querySelector(`[data-card-id="${cardId}"]`);
                    cardElement.style.opacity = '0.5';
                    cardElement.style.pointerEvents = 'none';
                    this.selectedCard = null;
                } else {
                    positionSlot.classList.add('incorrect');
                    // 显示正确位置
                    setTimeout(() => {
                        const correctSlot = document.querySelector(`[data-position="${data.correct_position}"]`);
                        correctSlot.classList.add('correct');
                        correctSlot.innerHTML = `${this.cards.find(c => c.id === cardId).pattern.emoji}<br>正确位置`;
                    }, 1000);
                }

                // 检查游戏是否结束
                if (data.game_phase === 'game_over') {
                    setTimeout(() => {
                        this.endGame();
                    }, 2000);
                }
            } else {
                this.showMessage(data.error || '检查失败', 'error');
            }
        } catch (error) {
            console.error('检查卡牌位置错误:', error);
            this.showMessage('网络错误，请重试', 'error');
        }
    }

    showCheckResult(data, guessedPosition) {
        const resultMessage = document.getElementById('resultMessage');
        resultMessage.className = 'result-message PolaroidEffect';

        if (data.is_correct) {
            resultMessage.classList.add('success');
        } else {
            resultMessage.classList.add('error');
        }

        resultMessage.innerHTML = `
            <div>${data.message}</div>
            ${!data.is_correct ? `<div style="margin-top: 10px; font-size: 0.9rem;">正确位置是: ${data.correct_position + 1}</div>` : ''}
            <div style="margin-top: 10px;">当前得分: ${data.score} | 剩余尝试: ${3 - data.attempts}</div>
        `;

        // 添加动画效果
        resultMessage.style.transform = 'scale(0)';
        resultMessage.style.opacity = '0';

        setTimeout(() => {
            resultMessage.style.transition = 'transform 0.5s ease, opacity 0.5s ease';
            resultMessage.style.transform = 'scale(1)';
            resultMessage.style.opacity = '1';
        }, 100);
    }

    clearResultMessage() {
        const resultMessage = document.getElementById('resultMessage');
        resultMessage.innerHTML = '';
        resultMessage.className = 'result-message PolaroidEffect';
    }

    async endGame() {
        try {
            const response = await fetch('/api/game_state');
            const data = await response.json();

            if (data.success) {
                this.showResultScreen(data.game_state);
            }
        } catch (error) {
            console.error('获取游戏状态错误:', error);
        }
    }

    showResultScreen(gameState) {
        this.showScreen('resultScreen');

        const finalScore = document.getElementById('finalScore');
        const resultTitle = document.getElementById('resultTitle');
        const performanceMessage = document.getElementById('performanceMessage');

        finalScore.textContent = gameState.score;

        // 根据分数显示不同消息
        if (gameState.score >= 80) {
            resultTitle.textContent = '太棒了！🎉';
            performanceMessage.innerHTML = '记忆力超群！你是记忆大师！<br>继续保持这种出色的表现！';
        } else if (gameState.score >= 60) {
            resultTitle.textContent = '做得不错！👏';
            performanceMessage.innerHTML = '你的记忆力很好！<br>再多练习一下就能成为专家了！';
        } else if (gameState.score >= 40) {
            resultTitle.textContent = '还可以！💪';
            performanceMessage.innerHTML = '继续努力！<br>相信下次会做得更好！';
        } else {
            resultTitle.textContent = '继续加油！🌟';
            performanceMessage.innerHTML = '记忆力需要多加练习<br>不要放弃，你一定能进步的！';
        }

        // 提交分数到排行榜
        this.submitScore(gameState.score);
    }

    async submitScore(score) {
        try {
            await fetch('/api/leaderboard', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify({
                    name: '玩家', // 实际项目中应该让用户输入名字
                    score: score
                })
            });
        } catch (error) {
            console.error('提交分数错误:', error);
        }
    }

    async showLeaderboard() {
        try {
            const response = await fetch('/api/leaderboard');
            const data = await response.json();

            if (data.success) {
                this.renderLeaderboard(data.scores);
                document.getElementById('leaderboardModal').style.display = 'block';
            }
        } catch (error) {
            console.error('获取排行榜错误:', error);
        }
    }

    renderLeaderboard(scores) {
        const leaderboardContent = document.getElementById('leaderboardContent');
        leaderboardContent.innerHTML = '';

        if (scores.length === 0) {
            leaderboardContent.innerHTML = '<p style="text-align: center; color: #666;">暂无记录</p>';
            return;
        }

        scores.forEach((score, index) => {
            const scoreElement = document.createElement('div');
            scoreElement.className = 'leaderboard-item';

            const rankIcon = index === 0 ? '🥇' : index === 1 ? '🥈' : index === 2 ? '🥉' : `${index + 1}`;

            scoreElement.innerHTML = `
                <span class="leaderboard-rank">${rankIcon}</span>
                <span class="leaderboard-name">${score.name}</span>
                <span class="leaderboard-score">${score.score}分</span>
                <span class="leaderboard-date">${score.date}</span>
            `;

            // 添加入场动画
            scoreElement.style.opacity = '0';
            scoreElement.style.transform = 'translateX(-20px)';
            leaderboardContent.appendChild(scoreElement);

            setTimeout(() => {
                scoreElement.style.transition = 'opacity 0.5s ease, transform 0.5s ease';
                scoreElement.style.opacity = '1';
                scoreElement.style.transform = 'translateX(0)';
            }, index * 100);
        });
    }

    closeModal() {
        document.getElementById('leaderboardModal').style.display = 'none';
    }

    resetGame() {
        this.gameState = null;
        this.selectedCard = null;
        this.cards = [];
        this.showScreen('startScreen');
        this.updateUI();
    }

    showScreen(screenId) {
        document.querySelectorAll('.game-screen').forEach(screen => {
            screen.classList.remove('active');
        });
        document.getElementById(screenId).classList.add('active');
    }

    updateUI() {
        // 更新分数和尝试次数
        document.getElementById('score').textContent = this.gameState ? this.gameState.score : 0;
        document.getElementById('attempts').textContent = this.gameState ? this.gameState.attempts : 0;
    }

    showMessage(message, type = 'info') {
        // 创建临时消息提示
        const messageDiv = document.createElement('div');
        messageDiv.style.cssText = `
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            background: ${type === 'error' ? 'linear-gradient(135deg, #FFB6C1 0%, #FFC0CB 100%)' : 'linear-gradient(135deg, #90EE90 0%, #98FB98 100%)'};
            color: ${type === 'error' ? '#8B0000' : '#006400'};
            border-radius: 10px;
            font-weight: bold;
            z-index: 2000;
            box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
            animation: slideIn 0.5s ease;
        `;
        messageDiv.textContent = message;

        document.body.appendChild(messageDiv);

        setTimeout(() => {
            messageDiv.style.animation = 'fadeOut 0.5s ease';
            setTimeout(() => {
                document.body.removeChild(messageDiv);
            }, 500);
        }, 3000);
    }
}

// 页面加载完成后初始化游戏
document.addEventListener('DOMContentLoaded', () => {
    window.game = new MemoryCardGame();

    // 添加一些页面装饰效果
    addPageDecorations();
});

// 页面装饰效果
function addPageDecorations() {
    // 添加随机飘落的装饰元素
    const decorations = ['🌟', '🎈', '🌈', '✨', '💫'];

    setInterval(() => {
        const decoration = document.createElement('div');
        decoration.textContent = decorations[Math.floor(Math.random() * decorations.length)];
        decoration.style.cssText = `
            position: fixed;
            top: -50px;
            left: ${Math.random() * window.innerWidth}px;
            font-size: ${Math.random() * 20 + 10}px;
            opacity: 0.7;
            z-index: 1;
            pointer-events: none;
            animation: fall ${Math.random() * 3 + 5}s linear;
        `;

        document.body.appendChild(decoration);

        setTimeout(() => {
            document.body.removeChild(decoration);
        }, 8000);
    }, 3000);
}

// 添加CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes fall {
        to {
            transform: translateY(100vh) rotate(360deg);
            opacity: 0;
        }
    }

    @keyframes fadeOut {
        to {
            opacity: 0;
            transform: translateY(-20px);
        }
    }

    @keyframes slideIn {
        from {
            opacity: 0;
            transform: translateX(100px);
        }
        to {
            opacity: 1;
            transform: translateX(0);
        }
    }
`;
document.head.appendChild(style);